import $ from '../jquery/jquery.min.js';
import ajax from '../utils/ajax'


const searchObj = {
    value: '',
    currentPage: 1,
    pageSize: 5,
    pages: 0,
    total: 0
}


showCarData();
showPageData();
//打开车位租赁合同
$('#carRental').on('click', '.show-customer-modal', function () {
    $('#add-carRental-contract-modalbox').show();
    if ($(this).text() == '编辑') {
        //获取选择要修改用户的数据渲染到模态框
        const _id = $(this).data('id');
        $('#car-title-p').addClass('gai');
        $('#car-title-p').attr('data-id', _id);
        getCarDatasById(_id);
    }else{
        $('#car-title-p').removeClass('gai');
        showCommunityCarSeats();
    }


});








//通过id查询对应的详细合同资料
function getCarDatasById(_id) {
    ajax({
        url: '/car/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                showCommunityCarSeatById(res.result.communityId._id);
                showSeatsByid(res.result.communityId._id,res.result.carportId._id);
                $('#car-price').val(res.result.price);
                $('#car-leasee').val(res.result.leasee);
                $('#car-leaseeContacts').val(res.result.leaseeContacts);
                $('#car-leaseeTel').val(res.result.leaseeTel);
                $('#car-Number').val(res.result.carNumber);
                $('#car-emissions').val(res.result.emissions);
                $('#car-contractNumber').val(res.result.contractNumber);
                $('#car-tenant').val(res.result.tenant);
                $('#car-signingDate').val(res.result.signingDate);
                $('#car-representative').val(res.result.representative);
                $('#car-tenantContacts').val(res.result.tenantContacts);
                $('#car-contractType').val(getDate());
                $('#car-term').val(res.result.term);
                $('#car-off_hire').val(res.result.off_hire);
                $('#car-start_date').val(res.result.start_date);
                $('#car-area').val(res.result.area);
                $('#car-earnestMoney').val(res.result.earnestMoney);
                $('#car-agencyfee').val(res.result.agencyfee);
                $('#car-isRentMoney').prop('checked',res.result.isRentMoney);
                $('#car-totalMoney').val(res.result.totalMoney);
                $('#car-increase').val(res.result.increase);
                $('#remark-input').val(res.result.earnestExplain);
                $('#upload-attachment-input').val(res.result.remark);
                $('#car-accessory').attr('src',res.result.accessory);
            } else {
                alert("获取客户数据失败");
            }
        }
    })
}




//关闭租赁合同
$('#return-btn').click(function () {
    $('#add-carRental-contract-modalbox').hide();
});


//新增合同||||||||修改合同
$('#save-contract-btn').click(function () {
    //获取当前输入框的值
    const communityId = $('#car-estate-select').val();
    const carportId = $('#carportNumber-select').val();
    const price = $('#car-price').val();
    const leasee = $('#car-leasee').val();
    const leaseeContacts = $('#car-leaseeContacts').val();
    const leaseeTel = $('#car-leaseeTel').val();
    const carNumber = $('#car-Number').val();
    const emissions = $('#car-emissions').val();
    const contractNumber = $('#car-contractNumber').val();
    const tenant = $('#car-tenant').val();
    const signingDate = $('#car-signingDate').val();
    const representative = $('#car-representative').val();
    const tenantContacts = $('#car-tenantContacts').val();
    const contractType = $('#car-contractType').val();
    const term = $('#car-term').val();
    const off_hire = $('#car-off_hire').val();
    const start_date = $('#car-start_date').val();
    const area = $('#car-area').val();
    const earnestMoney = $('#car-earnestMoney').val();
    const agencyfee = $('#car-agencyfee').val();
    const isRentMoney = $('#car-isRentMoney').prop('checked');
    const totalMoney = $('#car-isRentMoney').prop('checked') ? $('#car-totalMoney').val() : 0;
    const increase = $('#car-increase').val();
    const earnestExplain = $('#remark-input').val();
    const remark = $('#upload-attachment-input').val();
    const accessory = $('#car-accessory').attr('src');
    const contractName='车位租赁合同';
    if(price!=''&&leasee!=''&&leaseeContacts!=''&&leaseeTel!=''&&carNumber!=''&&emissions!=''&&contractNumber!=''&&tenant
    !=''&&signingDate!=''&&representative!=''&&tenantContacts!=''&&contractType!=''&&term!=''&&off_hire!=''&&start_date!=''&&area
    !=''&&earnestMoney!=''&&agencyfee!=''&&isRentMoney!=''&&totalMoney!=''&&increase!=''&&earnestExplain!=''&&remark!=''&&accessory!=''){
        if($('#car-title-p').prop('class')=='gai'){
            //编辑
            const _id = $('#car-title-p').data('id');
            ajax({
                url: '/car',
                type: "PUT",
                data: {
                    _id,
                    communityId,
                    carportId,
                    price,
                    leasee,
                    leaseeContacts,
                    leaseeTel,
                    carNumber,
                    emissions,
                    contractNumber,
                    tenant,
                    signingDate,
                    representative,
                    tenantContacts,
                    contractType,
                    term,
                    off_hire,
                    start_date,
                    area,
                    earnestMoney,
                    agencyfee,
                    isRentMoney,
                    totalMoney,
                    increase,
                    earnestExplain,
                    remark,
                    accessory
                },
                success(res) {
                    if (res.code == 200) {
                        alert("修改合同成功");
                        $('#add-carRental-contract-modalbox').hide();
                        showCarData();
                        clearData();
                    } else {
                        alert("修改合同失败");
                        $('#add-carRental-contract-modalbox').hide();
                        clearData();
                    }
                }
            });
        }else{
            //新增
            ajax({
                url: '/car',
                type: "POST",
                data: {
                    communityId,
                    carportId,
                    price,
                    leasee,
                    leaseeContacts,
                    leaseeTel,
                    carNumber,
                    emissions,
                    contractNumber,
                    tenant,
                    signingDate,
                    representative,
                    tenantContacts,
                    contractType,
                    term,
                    off_hire,
                    start_date,
                    area,
                    earnestMoney,
                    agencyfee,
                    isRentMoney,
                    totalMoney,
                    increase,
                    earnestExplain,
                    remark,
                    accessory,
                    contractName
                },
                success(res) {
                    if (res.code == 200) {
                        alert("新增合同成功");
                        const objs={
                            carId:res.data._id,
                            numbers:res.data.carportId.carportNumber, //资源名称
                            leaseeContacts:res.data.leaseeContacts,//联系人
                            contractNumber:res.data.contractNumber,//合同编号
                            contractName,
                             price:res.data.price,//收费金额  2
                            leaseeTel:res.data.leaseeTel,//联系电话   2
                            tenant:res.data.tenant, //租户  2
                            signingDate:res.data.signingDate,//签订日期  2
                            off_hire:res.data.off_hire,//停租日期   2
                            start_date:res.data.start_date,//起租日期`  2
                        }
                        addContracts(objs);
                        $('#add-carRental-contract-modalbox').hide();
                        if ($('#carport-tb tbody tr').length == searchObj.pageSize) {
                            showPageData();
                        }
                        showCarData();
                        clearData();
                    } else {
                        alert("新增合同失败");
                        $('#add-carRental-contract-modalbox').hide();
                        clearData();
                    }
                }
            });
        
        }
    }else{
        alert('输入框都不能为空!')
    }
});






//清除输入框数据
function clearData() {
    $('#car-price').val('');
    $('#car-leasee').val('');
    $('#car-leaseeContacts').val('');
    $('#car-leaseeTel').val('');
    $('#car-Number').val('');
    $('#car-emissions').val('');
    $('#car-contractNumber').val('');
    $('#car-tenant').val('');
    $('#car-signingDate').val('');
    $('#car-representative').val('');
    $('#car-tenantContacts').val('');
    $('#car-contractType').val('');
    $('#car-term').val('');
    $('#car-off_hire').val('');
    $('#car-start_date').val('');
    $('#car-area').val('');
    $('#car-earnestMoney').val('');
    $('#car-agencyfee').val('');
    $('#car-isRentMoney').prop('checked', false);
    $('#car-totalMoney').val('');
    $('#car-increase').val('');
    $('#remark-input').val('');
    $('#upload-attachment-input').val('');
    $('car-accessory').hide();
}


//渲染车位租赁合同数据
function showCarData() {
    ajax({
        url: "/car",
        type: 'GET',
        data: {
            searchObj,
            currentPage: searchObj.currentPage,
            pageSize: searchObj.pageSize,
        },
        success(res) {
            if (res.code == 200) {
                searchObj.pages = res.pages;
                searchObj.total = res.total;
                renderCardata(res.result);
            } 
        }
    })
}



// price:String,//收费金额
// leasee:String,//出租人,租赁方
// leaseeContacts:String,//联系人
// leaseeTel:String,//联系电话
// carNumber:String,//车辆号码
// emissions:String,//车辆排量
// contractNumber:String,//合同编号
// tenant:String, //租户
// signingDate:String,//签订日期
// representative:String,//法定代表
// tenantContacts:String,//租户联系人
// contractType:String,//合同状态
// term:String,//租期
// off_hire:String,//停租日期
// start_date:String,//起租日期
// area:String,//收费面积
// earnestMoney:String,//保证金
// agencyfee:String,//中介费
// isRentMoney:Boolean ,//是否收租
// totalMoney:String, //合同总价
// increase:String,//租金递增
// earnestExplain:String,//保证金说明
// remark:String,//备注
// accessory:String//附件

function renderCardata(data) {
    $('#carport-tb tbody').html(data.map(item => `<tr>
    <td>${item.carNumber}</td>
    <td>${item.communityId.communityName}</td>
    <td>${item.carportId.carportNumber}</td>
    <td>${item.leasee}</td>
    <td>${item.leaseeContacts}</td>
    <td>${item.leaseeTel}</td>
    <td>${item.start_date}</td>
    <td>${item.off_hire}</td>
    <td>${getType(item.start_date, getDate(), item.off_hire) ? '进行中' : "已过期"}</td>
    <td>${item.emissions}</td>
    <td>1</td>
    <td>￥${item.price}/月</td>
    <td><span data-id=${item._id} class='car-detail-btn' >详情</span><span class='show-customer-modal' data-id=${item._id}>编辑</span><span data-id=${item._id} class='del-car-btn'>删除</span></td>
</tr>`).join(''));
}

//获取当前日期
function getDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = parseInt(date.getMonth()) + 1;
    const day = date.getDate();
    return `${year}-0${month}-${day}`;
}

//判断合同状态
function getType(data1, data2, data3) {
    const date1 = new Date(data1);
    const date2 = new Date(data2);
    const date3 = new Date(data3);
    if (date2 >= date1 && date2 <= date3) {
        return true;
    } else {
        return false;
    }
}





//点击删除按钮，删除对应客户数据
$('#carport-tb tbody').on('click', '.del-car-btn', function () {
    const _id = $(this).data('id');
    delCarData(_id);
});


//删除客户数据
function delCarData(_id) {
    ajax({
        url: '/car',
        data: { _id },
        type: "DELETE",
        success(res) {
            if (res.code == 200) {
                // 删除成功
                if ((searchObj.total) % (searchObj.pageSize) == 1) {
                    $('#carport-tb tbody tr').length == 1 ? searchObj.currentPage-- : searchObj.currentPage;
                    showPageData();
                }
                showCarData();
            } else {
                alert('抱歉,删除失败');
            }
        }
    })
}


//渲染下面条数控制的页面
function showPageData() {
    ajax({
        url: "/car",
        type: 'GET',
        data: {
            searchObj,
            currentPage: searchObj.currentPage,
            pageSize: searchObj.pageSize,
        },
        success(res) {
            if (res.code == 200) {
                renderPageData(Number(res.pages));
            } 
        }
    })
}

function renderPageData(pages) {
    let html = '';
    for (let i = 1; i <= pages; i++) {
        html += `<span>${i}</span>`;
    }
    $('#carRental-bottom-choose-page-div .add-pages-span').html(html);
    $('#carRental-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#carRental-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
}




//点击切换页面
$('#carRental-bottom-choose-page-div .add-pages-span').on('click', 'span', function () {
    $('#carRental-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(this).addClass('active');
    const currentPage = $(this).text();
    searchObj.currentPage = Number(currentPage);
    showCarData();
});

//点击切换页面显示条数
$('#car-pageSize-select').change(function () {
    const pageSize = $('#car-pageSize-select').val();
    searchObj.pageSize = Number(pageSize);
    searchObj.currentPage = 1;
    showCarData();
    showPageData();
});


//跳至X页事件
$('#car-go-page').keyup(function (e) {
    if (e.keyCode == 13) {
        const page = $('#car-go-page').val();
        if (page != '' && typeof Number(page) == 'number' && !isNaN(Number(page))) {
            if (Number(page) < 1) {
                searchObj.currentPage = 1;
                showCarData();
                $('#carRental-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#carRental-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            } else if (Number(page) > searchObj.pages) {
                searchObj.currentPage = searchObj.pages;
                showCarData();
                $('#carRental-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#carRental-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            } else {
                searchObj.currentPage = Number(page);
                showCarData();
                $('#carRental-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#carRental-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            }
        }
    }
});


//上一页，下一页事件
$('#car-prev-span').click(function () {
    if (searchObj.currentPage <= 1) {
        searchObj.currentPage = 1;
    } else {
        searchObj.currentPage--;
    }
    showCarData();
    $('#carRental-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#carRental-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
});

$('#car-next-span').click(function () {
    if (searchObj.currentPage == searchObj.pages) {
        searchObj.currentPage = searchObj.pages;
    } else {
        searchObj.currentPage++;
    }
    showCarData();
    $('#carRental-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#carRental-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
});


//点击搜索按钮查询
$('#search-car-btn').click(function () {
    const value = $('#car-search').val();
    searchObj.value = value;
    searchObj.currentPage = 1;
    showCarData();
    showPageData();
});


//点击详情查询合同图片
$('#carport-tb tbody').on('click', '.car-detail-btn', function () {
    const _id = $(this).data('id');
    getCustomerById(_id);
});









//通过id查询对应的车位租赁合同图片数据
function getCustomerById(_id) {
    ajax({
        url: '/car/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                $('#show-img-div').show();
                $('#cancle-img').attr('src', res.result.accessory);
            } 
        }
    })
}


$('#cancle-img-div').click(function () {
    $('#show-img-div').hide();
    $('#cancle-img').attr('src', '');
});



//上传图片
$('#file-input').change(function (e) {
    const files = e.target.files;
    const fd = new FormData();
    fd.append('file', files[0]);
    $.ajax({
        url: 'http://localhost:3100/car/uploadImages',
        type: "POST",
        data: fd,
        contentType: false,
        processData: false,
        cache: false,
        success(res) {
            if (res.code == 200) {
                $('#car-accessory').attr('src', 'http://localhost:3100/' + res.data);
            }
        }
    });
});




//渲染小区
function showCommunityCarSeats() {
    ajax({
        url: '/community',
        type: "GET",
        data: { value: '' },
        success(res) {
            if (res.code == 200) {
                //设置小区选择
                showSeats(res.result[0]._id)
                $('#car-estate-select').html(res.result.map(item => `<option value=${item._id}>${item.communityName}</option>`).join(''));
            }
        }
    })
}


//渲染指定小区
function showCommunityCarSeatById(_id) {
    ajax({
        url: '/community',
        type: "GET",
        data: { value: '' },
        success(res) {
            if (res.code == 200) {
                $('#car-estate-select').html(res.result.map(item => `<option value=${item._id}>${item.communityName}</option>`).join(''));
                $('#car-estate-select').val(_id);
            }
        }
    })
}


//渲染车位根据id
function showSeats(_id) {
    ajax({
        url: '/parkingSpace/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                //设置车位选择
                $('#carportNumber-select').html(res.result.map(item => `<option value=${item._id}>${item.carportNumber}</option>`).join(''));
            }
        }
    })
}



//渲染指定的车位根据id
function showSeatsByid(_id,ids) {
    ajax({
        url: '/parkingSpace/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                //设置车位选择
                $('#carportNumber-select').html(res.result.map(item => `<option value=${item._id}>${item.carportNumber}</option>`).join(''));
                $('#carportNumber-select').val(ids);
            }
        }
    })
}


//小区下拉框的选择事件
$('#car-estate-select').change(function () {
    const id = $('#car-estate-select').val();
    showSeats(id);
});




//添加数据到合同管理集合
function addContracts(obj){
    ajax({
        url:'/contracts',
        type:'POST',
        data:obj,
        success(res){
        }
    });
}








